package com.cuntian.netty.processor;

import com.cuntian.enums.IMCmdType;
import com.cuntian.model.IMRecvInfo;
import com.cuntian.model.IMSendInfo;
import com.cuntian.model.IMUserInfo;
import com.cuntian.netty.UserChannelCtxMap;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class GroupMessageProcessor extends AbstractMessageProcessor<IMRecvInfo> {

    @Override
    public void process(IMRecvInfo recvInfo) {
        //发送方
        IMUserInfo sender = recvInfo.getSender();
        //消息接受方
        List<IMUserInfo> receivers = recvInfo.getReceivers();
        log.info("接收到群消息，发送者:{},接收用户数量:{}，内容:{}", sender.getId(), receivers.size(), recvInfo.getData());
        for (IMUserInfo receiver : receivers) {
            try {
                // 通过用户的id和终端id 查询到需要的channel
                ChannelHandlerContext channelCtx = UserChannelCtxMap.getChannelCtx(receiver.getId(), receiver.getTerminal());
                if(!Objects.isNull(channelCtx)){
                    // 推送消息到用户
                    IMSendInfo<Object> sendInfo = new IMSendInfo<>();
                    sendInfo.setCmd(IMCmdType.GROUP_MESSAGE.code());
                    sendInfo.setData(recvInfo.getData());
                    // 向channel中推送消息
                    channelCtx.channel().writeAndFlush(sendInfo);
                }else{
                    log.error("未找到channel,发送者:{},接收id:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
                }
            } catch (Exception e){
                // 消息发送失败确认
                log.error("发送消息异常,发送者:{},接收id:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
            }
        }
    }

}
